from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models import Conversation, Message, db
import datetime

conversation_bp = Blueprint('conversation', __name__)

@conversation_bp.route('/api/conversations', methods=['GET'])
@jwt_required()
def get_conversations():
    user_id = get_jwt_identity()
    page = request.args.get('page', 1, type=int)
    per_page = 20
    
    # 查询最近对话（按最后更新时间排序）
    conversations = Conversation.query.filter_by(user_id=user_id)\
        .order_by(Conversation.updated_at.desc())\
        .paginate(page=page, per_page=per_page)
    
    return jsonify({
        'data': [{
            'id': c.id,
            'title': c.title or f'对话 {c.created_at.strftime("%Y-%m-%d")}',
            'last_message': c.messages[-1].content if c.messages else ''
        } for c in conversations.items],
        'total_pages': conversations.pages
    })

@conversation_bp.route('/api/conversations/<int:convo_id>/messages', methods=['GET'])
@jwt_required()
def get_messages(convo_id):
    user_id = get_jwt_identity()
    # 验证对话归属权
    conversation = Conversation.query.filter_by(id=convo_id, user_id=user_id).first()
    if not conversation:
        return jsonify(code=404, msg='对话不存在'), 404
    
    messages = Message.query.filter_by(conversation_id=convo_id)\
        .order_by(Message.created_at.asc())\
        .all()
    
    return jsonify({
        'data': [{
            'id': m.id,
            'role': m.role,
            'content': m.content,
            'created_at': m.created_at.isoformat()
        } for m in messages]
    })